package com.iwhalecloud.bss.kite.cucc.service.attr.linkhandler;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteObjectUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.DecimalCalc;
import com.iwhalecloud.bss.kite.cucc.common.util.StrTools;
import com.iwhalecloud.bss.kite.cucc.service.attr.handler.LocalSubscriptionFeeAttrHandler;
import com.iwhalecloud.bss.kite.cucc.spec.impl.transfer.GoodsInfoTransfer;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.dataservice.cache.ProductCache;
import com.iwhalecloud.bss.kite.listener.handler.attr.annotation.AttrHandler;
import com.iwhalecloud.bss.kite.listener.handler.attr.impl.AbstractAttrLinkageHandler;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.dto.KiteInstRelDTO;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.enums.InstType;
import com.iwhalecloud.bss.kite.manager.inst.*;
import com.iwhalecloud.bss.kite.service.attr.AttrData;
import com.iwhalecloud.bss.kite.service.scene.attr.OperateInstAttrService;
import com.ztesoft.bss.common.util.ContextUtil;
import edu.emory.mathcs.backport.java.util.Collections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 *
 */
@Service
@AttrHandler(LocalSubscriptionFeeAttrHandler.class)
public class LocalSubscriptionFeeAttrLinkHandler extends AbstractAttrLinkageHandler<AttrData> {
    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Autowired
    OperateInstAttrService operateInstAttrService;

    @Override
    public void handle(KiteAttr attr, KiteInst inst, AttrData data) {
        //模版还原时，不做校验
        Map<String, Object> extParams = ContextUtil.getLoginInfo().getUserInfo().getExtParams();
        //fixme 可能导致频繁访问缓存,上线临时处理方案
        if ("sceneTempl".equals(data.getExtAttributes().get("entry")) || (KiteMapUtils.isNotEmpty(extParams) && extParams.containsKey("nodeCode"))) {
            return;
        }
        if (inst instanceof KiteProdInstFunc) {
            KiteProdInstFunc kiteProdInstFunc = (KiteProdInstFunc) inst;
            // 去所有资费功能产品,获取所有的标准价格
            List<KiteProdInstFunc> kiteProdInstFuncList = getBaseNewFuncProd(data, kiteProdInstFunc.getAccProdInstId());
            // 获取灵活系数
            String lingHuoXiShu = null;
            final String[] num = new String[1];
            num[0] = "0";
            List<KiteProdInstFunc> kiteZheKouFuncList = getZheKouFuncProd(data, kiteProdInstFunc.getAccProdInstId());
            if (KiteListUtils.isNotEmpty(kiteZheKouFuncList)) {
                KiteAttr kiteAttrs = kiteZheKouFuncList.get(0).getAttr("200003713");
                if (!KiteObjectUtils.isEmpty(kiteAttrs)) {
                    lingHuoXiShu = kiteAttrs.getValue();
                }
            }
            if (KiteListUtils.isNotEmpty(kiteProdInstFuncList)) {
                String finalLingHuoXiShu = lingHuoXiShu;
                kiteProdInstFuncList.stream().forEach(kiteProdInst -> {
                    KiteAttr kiteAttrs = kiteProdInst.getAttr("200002773"); //标准价格
                    if (!KiteObjectUtils.isEmpty(kiteAttrs)) {
                        String bZPrice = kiteAttrs.getValue();
                        num[0] = StrTools.numAdd(num[0], StrTools.numMultiply(bZPrice, finalLingHuoXiShu));
                    }
                });
            }

            // 计算平台服务级别费率
            if (KiteStringUtils.isNotEmpty(num[0])) {
                Double platFromFuncFee = this.getPlatformFuncFee(data.getSceneInstId(), data.getCustId());
                num[0] = DecimalCalc.mul(Double.valueOf(num[0]), (1 + DecimalCalc.div(platFromFuncFee, 100))) + "";
            }

            num[0] = StrTools.numAdd(num[0], String.valueOf(countLaixianFee(data.getSceneInstId())));

            operateInstAttrService
                .setAttrValue(kiteZheKouFuncList.get(0), "200003715", num[0], data.getSceneInstId(), JSON.toJSONString(data));
        }
    }

    @Override
    public void handleStyle(KiteAttr attr, KiteInst inst, AttrData data) {

    }

    public int countLaixianFee(String sceneInstId) {
        int laixianFee = 0;
        List<KiteProdInstFunc> prodInstFuncs = this.querySceneInstService.listInsts(sceneInstId, Collections.singletonList(InstType.PROD_INST_FUNC));
        prodInstFuncs.removeIf(inst -> !KiteStringUtils.equalsAny(ProductCache.get(inst.getSpecId()).getProdNbr(), "300000151", LocalKeyConsts.FUNC_PROD_ID_YF5GTX));
        if (!KiteListUtils.isEmpty(prodInstFuncs)) {
            // 通讯类型200003688
            // 是否开通来显200003693，开通100006426
            for (KiteProdInstFunc inst : prodInstFuncs) {
                if (KiteStringUtils.equalsAny(inst.getActionType().name(), ActionType.X.name(), ActionType.D.name())) {
                    continue;
                }
                String commuType = inst.getAttrValue("200003688");
                String orderLaixian = inst.getAttrValue("200003693");
                if (!KiteStringUtils.isEmpty(commuType) && KiteStringUtils.equalsAny(commuType, "100006422", "100006424")
                    && KiteStringUtils.equals(orderLaixian, "100006426")) {
                    laixianFee += 5;
                }
            }
        }
        return laixianFee;
    }

    private List<KiteProdInstFunc> getBaseNewFuncProd(AttrData data, String prodInstId) {
        List<KiteProdInstFunc> zfKiteProdInstFuncs = Lists.newArrayList(); // 取所有接入类产品
        List<KiteProdInstFunc> kiteProdInstFuncList = querySceneInstService
            .listProdInstFuncsByProdId(data.getCustId(), prodInstId, "300000171");
        if (KiteListUtils.isEmpty(kiteProdInstFuncList)) {
            kiteProdInstFuncList = querySceneInstService
                .listProdInstFuncsByProdId(data.getCustId(), prodInstId, "30000017111");
        }
        if (KiteListUtils.isEmpty(kiteProdInstFuncList)) {
            kiteProdInstFuncList = querySceneInstService
                .listProdInstFuncsByProdId(data.getCustId(), prodInstId, "30000017112");
        }
        if (KiteListUtils.isEmpty(kiteProdInstFuncList)) {
            kiteProdInstFuncList = querySceneInstService
                .listProdInstFuncsByProdId(data.getCustId(), prodInstId, LocalKeyConsts.FUNC_PROD_ID_YF5GZF_FW);
        }
        if (KiteListUtils.isNotEmpty(kiteProdInstFuncList)) {
            zfKiteProdInstFuncs.addAll(kiteProdInstFuncList);
        }
        return zfKiteProdInstFuncs;
    }

    private List<KiteProdInstFunc> getZheKouFuncProd(AttrData data, String prodInstId) {
        List<KiteProdInstFunc> zfKiteProdInstFuncs = Lists.newArrayList(); // 取所有接入类产品
        List<KiteProdInstFunc> kiteProdInstFuncList = querySceneInstService
            .listProdInstFuncsByProdId(data.getCustId(), prodInstId, "300000172");
        if (KiteListUtils.isEmpty(kiteProdInstFuncList)) {
            kiteProdInstFuncList = querySceneInstService
                .listProdInstFuncsByProdId(data.getCustId(), prodInstId, "30000017211");
        }
        if (KiteListUtils.isEmpty(kiteProdInstFuncList)) {
            kiteProdInstFuncList = querySceneInstService
                .listProdInstFuncsByProdId(data.getCustId(), prodInstId, "30000017212");
        }
        if (KiteListUtils.isEmpty(kiteProdInstFuncList)) {
            kiteProdInstFuncList = querySceneInstService
                .listProdInstFuncsByProdId(data.getCustId(), prodInstId, LocalKeyConsts.FUNC_PROD_ID_YF5GZF_ZK);
        }
        if (KiteListUtils.isNotEmpty(kiteProdInstFuncList)) {
            zfKiteProdInstFuncs.addAll(kiteProdInstFuncList);
        }
        return zfKiteProdInstFuncs;
    }

    private Double getPlatformFuncFee(String sceneInstId, String custId) {
        String platFromFuncFee = KeyConsts.ZERO;
        KiteOfferInst mainOfferInst = querySceneInstService.getMainOfferInst(sceneInstId);
        List<KiteInstRelDTO> instRels = querySceneInstService.listInstRelsByAInst(custId, InstType.MAIN_OFFER_INST, mainOfferInst.getOfferInstId(), InstType.PROD_INST);
        if (!KiteListUtils.isEmpty(instRels)) {
            for (KiteInstRelDTO rel : instRels) {
                KiteProdInst prodInst = this.querySceneInstService.getProdInst(custId, rel.getzInstId());
                if (!KiteObjectUtils.isEmpty(prodInst) && !GoodsInfoTransfer.isAddRoleOffer(mainOfferInst.getSpecId(), OfferCache.get(mainOfferInst.getSpecId()).getCateId()) && !LocalKeyConsts.PROD_USE_TYPE_2000.equals(ProductCache.get(prodInst.getSpecId()).getProdUseType())) {
                    String platFromServLevel = prodInst.getAttrValue("200003681");
                    //平台功能费
                    platFromFuncFee = prodInst.getAttrValue("200004024");
                    if(KiteStringUtils.isEmpty(platFromFuncFee)) {
                        platFromFuncFee = KeyConsts.ZERO;
                    }
                    //基础服务，平台功能费0
                    if ("100006416".equals(platFromServLevel)) {
                        platFromFuncFee = KeyConsts.ZERO;
                    }
                }
            }
        }
        return Double.valueOf(platFromFuncFee);
    }

}
